Skip to main content

Classes

Python is a class-based inheritance language. In simple terms, classes are blueprints to create objects.

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age

def bark(self):
return f"{self.name} says Woof!"

# Creating a dog object
my_dog = Dog("Buddy", 3)
print(my_dog.bark()) # Output: Buddy says Woof!

1. __init__ method

The __init__ method is Python’s special initialization method (sometimes called a constructor). When you create a new object from a class, Python automatically calls this method to set up the initial state of the object.

my_dog = Dog("Buddy", 3)

→ When Python executes this line, it:

  • Creates a new empty object
  • Calls __init__ with the provided arguments
  • Returns the initialized object

2. self

In Python, self represents the specific instance of the class that’s being worked with. It's how the code knows which object's data to access or modify. Every instance method in a class automatically receives the instance (self) as the first parameter.

def bark(self):
return f"{self.name} says Woof!"

Example:

class Library:
def __init__(self, name):
self.name = name
self.books = [] # Each library has its own book list

def add_book(self, book):
# self.books refers to THIS library's book list
self.books.append(book)

def book_count(self):
# Returns the count for THIS specific library
return len(self.books)

# Creating two different libraries
city_library = Library("City Library")
school_library = Library("School Library")

# Adding books to different libraries
city_library.add_book(gatsby) # Adds to city_library's books list
school_library.add_book(hobbit) # Adds to school_library's books list

# Each library has its own separate count
print(city_library.book_count()) # 1
print(school_library.book_count()) # 1

While it's convention to use the name self, Python cares about the position, not the name. This code would work the same way:

class Library:
def __init__(this_library, name): # "this_library" instead of "self"
this_library.name = name
this_library.books = []